<?php
class Posting extends Config
{
	var $page;
	var $allFields;
	var $tableName = "blog";
	var $errors;
	
	function newPost($message, $title, $tags, $url)
	{
		try
		{
			$url = $this -> checkUrl($url);
			$queryText = "INSERT INTO `". $this -> DB_PREFIX . $this -> tableName ."` SET 
				`message`= '". mysql_real_escape_string($message) . "',
				`title` = '" . mysql_real_escape_string($title) . "',
				`tags` = '" . mysql_real_escape_string($tags) . "',
				`url` = '" . mysql_real_escape_string($url) . "',
				`date` = '". date(" d.m.y G:i ") ."',
				`time` = '". time() ."'";
			$this -> sql($queryText);
			//add or increment his tags from DB
			$myTags = new Tags;
			$myTags -> inputTagsString = $tags;
			$myTags -> addPost();
			echo '<td class="offer">Запись сохранена!</td>';
		}
		catch (Exception $e)
		{
			return "Error in insert";
		}
	}
	
	function updateComment($commentId, $action)
	{
		$commentId = intval($commentId);
		switch($action)
		{
			case 'newToOn':
				$cQuery = "UPDATE `". $this -> DB_PREFIX ."comments` comment
							JOIN `". $this -> DB_PREFIX . $this -> tableName ."` blog ON blog.`id` = comment.`post_id` 
							SET comment.`stat` = '1', 
							blog.`comments` = comments + 1
							WHERE comment.`id` = '". $commentId ."';";
				break;
			case 'newToCart':
				$cQuery = "UPDATE `comments` 
							SET `stat` = '0' 
							WHERE `id` = '". $commentId ."';";
				break;
			case 'onToNew':
				$cQuery = "UPDATE `comments` comment
							JOIN `". $this -> DB_PREFIX . $this -> tableName ."` blog ON blog.`id` = comment.`post_id` 
							SET comment.`stat` = '2', 
							blog.`comments` = comments - 1
							WHERE comment.`id` = '". $commentId ."';";
				break;
			case 'onToCart':
				$cQuery = "UPDATE `comments` comment
							JOIN `". $this -> DB_PREFIX . $this -> tableName ."` blog ON blog.`id` = comment.`post_id` 
							SET comment.`stat` = '0', 
							blog.`comments` = comments - 1
							WHERE comment.`id` = '". $commentId ."';";
				break;
			case 'cartToOn':
				$cQuery = "UPDATE `comments` comment
							JOIN `". $this -> DB_PREFIX . $this -> tableName ."` blog ON blog.`id` = comment.`post_id` 
							SET comment.`stat` = '1', 
							blog.`comments` = comments + 1
							WHERE comment.`id` = '". $commentId ."';";
				break;
			case 'cartToNew':
				$cQuery = "UPDATE `comments` 
							SET `stat` = '2' 
							WHERE `id` = '". $commentId ."';";
				break;
			case 'cartDelete':
				$cQuery = "DELETE FROM `comments` 
							WHERE `id` = '". $commentId ."';";
				break;
			case 'massDelete':
				$cQuery = "DELETE FROM `comments` 
							WHERE `id` = '". $commentId ."';";
				break;
		}
		$this -> sql($cQuery);
	}
	
	function commentAdd($message, $postId, $mail, $author)
	{
		$mes = trim($message);
		$postId = intval($postId);
		$author = trim($author);
		$mail = strtolower(trim($mail));
		
		//обрабатываем ошибки
		$data = $this -> sql( "SELECT `id` FROM `". $this -> DB_PREFIX . $this -> tableName ."` WHERE `id` = '" .$postId ."' LIMIT 1" );
		if (mysql_num_rows($data) != 1)
			$stop = 'В базе нет такого поста!<br />';
		if (strlen($mes) > 350)
			$stop .= 'Слишком длинный комментарий!<br />';
		if (strlen($mes) < 7)
			$stop .= 'Слишком короткий комментарий!<br />';
		if (strlen($author) > 25)
			$stop .= 'Слишком длиннное имя!<br />';
		if (strlen($author) < 3)
			$stop .= 'Слишком короткое имя!<br />';
		if ( !preg_match("|^([a-z0-9_\.\-]{1,20})@([a-z0-9\.\-]{1,20})\.([a-z]{2,4})|is", $mail))
			$stop .= 'Неверно указан адрес почтового ящика!<br />';
		if ($_SESSION['last_blog'] + 40 > time())
			$stop .= 'Слишком частый постинг!<br />';
		$data = $this -> sql( "SELECT `id` FROM `". $this -> DB_PREFIX ."comments` WHERE `comment` = '" .$mes ."' LIMIT 1" );
		if (mysql_num_rows($data) == 1)
			$stop .= 'Ваш последний комментарий был таким же!<br />';
		
		//предохраняемся
		$author = htmlspecialchars($author);
		$mes = htmlspecialchars($mes);
		$mail = htmlspecialchars($mail);
		
		
		if (empty($stop)) {
			//define user location
			//if on geoip functions
			if (GEOIP == 1) 
			{
				require_once (DOCDIR . MYDIR ."includes/modules/geoip/geoipcity.inc");
				require_once (DOCDIR . MYDIR ."/includes/modules/geoip/geoipregionvars.php");
				
				$gi = geoip_open(DOCDIR . MYDIR ."/includes/modules/geoip/GeoLiteCity.dat",GEOIP_STANDARD);
				$record = geoip_record_by_addr($gi, $_SERVER['REMOTE_ADDR']);
				$ucountry = $record->country_name ;
				$uregion = $GEOIP_REGION_NAME[$record->country_code][$record->region];
				$ucity = $record->city;
				geoip_close($gi);
				//if user from russia - translate location
				if ($ucountry == 'Russian Federation') 
				{
					//$localize = latrus($uregion) ." / ". latrus($ucity); // ИСПРАВИТЬ!!!
					$localize = $uregion ." / ". $ucity;
					$localize = "Российская Федерация" ." / ". iconv('cp1251', 'utf-8//IGNORE//TRANSLIT', $localize);
				} 
				else 
				{
					$localize = $ucountry ." / ". $uregion ." / ". $ucity;
				}
				$country_code = $record->country_code;
			}
			else 
			{
				$country_code = "";
				$localize = "";
			}
			
			$this -> sql( "INSERT INTO `". $this -> DB_PREFIX ."comments` SET 
						`comment`= '". mysql_real_escape_string($mes) . "',
						`ip`= '". $_SERVER['REMOTE_ADDR'] . "',
						`post_id`= '". $postId . "',
						`mail` = '" . $mail . "',
						`local` = '" . $localize . "',
						`country_code` = '" . $country_code . "',
						`author` = '". mysql_real_escape_string($author) . "',
						`date` = '". date(" d.m.y G:i:s ") ."';" );
			$_SESSION['last_blog'] = time();
			return 'Комментарий добавлен';
		} 
		else 
		{
			return $stop;
		}
	}
	
	function updatePost($postId, $message, $title, $tags, $url)
	{
		try
		{
			$postId = intval($postId);
			$url = $this -> checkUrl($url);
			$queryText = "UPDATE `". $this -> DB_PREFIX . $this -> tableName ."` SET 
				`message`= '". mysql_real_escape_string($message) . "',
				`title` = '" . mysql_real_escape_string($title) . "',
				`tags` = '" . mysql_real_escape_string($tags) . "',
				`url` = '" . mysql_real_escape_string($url) . "'
				WHERE `id` = '". $postId ."'";
			$this -> sql($queryText);
			return 'Запись обновлена!';
		}
		catch (Exception $e)
		{
			return 'Ошибка при обновлении';
		}
	}
	
	function deletePost($postId)
	{
		try
		{
			$postId = intval($postId);
			//delete or decrement his tags from DB
			$dQuery = "SELECT * FROM `". $this -> DB_PREFIX . $this -> tableName ."` WHERE `id` = '". $postId ."'";
			$dSelect = $this -> sql($dQuery);
			$dData = mysql_fetch_array($dSelect);
			$myTags = new Tags;
			$myTags -> inputTagsString = $dData['tags'];
			$myTags -> delPost();
			//delete topic
			$bQuery = "DELETE FROM `". $this -> DB_PREFIX . $this -> tableName ."` WHERE `id` = '". $postId ."';";
			$this -> sql($bQuery);
			//and delete his comments:
			$cQuery = "DELETE FROM `". $this -> DB_PREFIX ."comments` WHERE `post_id` = '". $postId ."';";
			$this -> sql($cQuery);
			
			return 'Запись удалена';
		}
		catch (Exception $e)
		{
			return 'Произошла ошибка при удалении';
		}
	}
	
	function checkUrl($url) //input or add numbering post url
	{
		$checkQuery = "SELECT COUNT(*) FROM `". $this -> DB_PREFIX . $this -> tableName ."` WHERE `url` = '". mysql_real_escape_string($url) ."'";
		$query = $this -> sql($checkQuery);
		$data = mysql_fetch_array($query);
		if ($data['COUNT(*)'] != 0)
		{
			$i = 1;
			do
			{
				$query1 = $this -> sql("SELECT COUNT(*) FROM `". $this -> DB_PREFIX . $this -> tableName ."` 
										WHERE `url` = '". mysql_real_escape_string($url) . ++$i ."'");
				$data1 = mysql_fetch_array($query1);
			}
			while ($data1['COUNT(*)'] != 0);
			$url = $url . $i;
		}
		return urlencode($url);
	}
	
}

?>